<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数字人测试页面</title>
    <style>
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        #rtc {
            width: 100%;
            height: 450px;
            background: #000;
            margin-bottom: 20px;
        }
        .controls {
            margin-bottom: 20px;
        }
        .input-group {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
        }
        .input-group input {
            flex: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .input-group button {
            padding: 8px 16px;
        }
        .status {
            margin-bottom: 20px;
            padding: 10px;
            background: #f5f5f5;
        }
        #log {
            height: 200px;
            overflow-y: auto;
            background: #f5f5f5;
            padding: 10px;
            font-family: monospace;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>数字人测试页面</h1>
        <video id="rtc" autoplay playsinline></video>
        <div class="controls">
            <button id="initBtn">初始化</button>
            <button id="startRecordBtn">开始录音</button>
            <button id="stopRecordBtn">停止录音</button>
            <button id="destroyBtn">销毁实例</button>
        </div>
        <div class="input-group">
            <input type="text" id="textInput" placeholder="请输入要发送的文本" value="查询杭州天气">
            <button id="sendTextBtn">发送文本</button>
        </div>
        <div class="status">
            <div>状态: <span id="status">未初始化</span></div>
        </div>
        <div id="log"></div>
    </div>

    <script src="https://g.alicdn.com/code/npm/@alife/aliyun-avatar-sdk/1.0.20/index.js"></script>
    <script>
        // 日志函数
        function log(message, type = 'info') {
            const logDiv = document.getElementById('log');
            const time = new Date().toLocaleTimeString();
            const div = document.createElement('div');
            div.style.color = type === 'error' ? 'red' : type === 'warning' ? 'orange' : 'black';
            div.textContent = `[${time}] ${message}`;
            logDiv.appendChild(div);
            logDiv.scrollTop = logDiv.scrollHeight;
        }

        // 更新状态
        function updateStatus(message) {
            document.getElementById('status').textContent = message;
        }

        const DialogAvatarSDK = window.DialogAvatarSDK;
        let dialogAvatarSDK = null;

        // 初始化SDK
        async function initSDK() {
            try {
                updateStatus('正在创建会话...');
                
                // 从后端获取会话信息
                const response = await fetch('/api/avatar/session', {
                    method: 'POST'
                });
                
                if (!response.ok) {
                    throw new Error('创建会话失败: ' + response.statusText);
                }
                
                const data = await response.json();
                log('会话创建成功: ' + JSON.stringify(data, null, 2));

                const { sessionId, token, channel } = data;

                // 创建SDK实例
                dialogAvatarSDK = new DialogAvatarSDK({
                    tenantId: '29813',
                    appId: '3dtvj85575',
                    sessionId: sessionId,
                    token: token,
                    channel: {
                        appId: channel.appId,
                        channelId: channel.channelId,
                        expiredTime: channel.expiredTime,
                        gslb: channel.gslb,
                        nonce: channel.nonce,
                        token: channel.token,
                        type: channel.type,
                        userId: channel.userId
                    },
                    videoDOM: document.getElementById('rtc'),
                    options: {
                        wsUrl: "wss://avatar-im.console.aliyun.com/ws",
                        maxReconnectTimeout: 300000,
                        audio: {
                            autoStartRecord: false,
                            interval: 100,
                            autoDodge: false
                        },
                        rtc: {
                            muted: false
                        }
                    },
                    onInitSuccess: () => {
                        log('IM连接成功，RTC拉流成功');
                        updateStatus('已连接');
                        log('aliRtcEngine实例：', dialogAvatarSDK.rtc.aliRtcEngine);
                    },
                    onRtcInitSuccess: () => {
                        log('RTC拉流成功，等待IM链接...');
                        log('aliRtcEngine实例：', dialogAvatarSDK.rtc.aliRtcEngine);
                    },
                    onIMInitSuccess: () => {
                        log('IM连接成功，等待RTC拉流...');
                    },
                    onError: (error) => {
                        log('错误: ' + JSON.stringify(error), 'error');
                        updateStatus('发生错误');
                    },
                    onWarning: (msg) => {
                        log('警告: ' + msg, 'warning');
                    },
                    onRecordingStart: () => {
                        log('录音开始');
                        updateStatus('录音中');
                    },
                    onRecordingStop: () => {
                        log('录音停止');
                        updateStatus('已连接');
                    },
                    onASR: (text, sentenceId) => {
                        log(`ASR识别文本: ${text} (ID: ${sentenceId})`);
                    },
                    onAnswer: (text, sentenceId) => {
                        log(`数字人回答: ${text} (ID: ${sentenceId})`);
                    },
                    onUnknownIMMessage: (msg) => {
                        log('未知IM消息: ' + JSON.stringify(msg));
                    }
                });

                // 初始化
                await dialogAvatarSDK.init();
                log('SDK初始化成功');
                updateStatus('已连接');
            } catch (error) {
                log('初始化失败: ' + error.message, 'error');
                updateStatus('初始化失败');
            }
        }

        // 绑定按钮事件
        document.getElementById('initBtn').onclick = initSDK;
        
        document.getElementById('startRecordBtn').onclick = async () => {
            if (!dialogAvatarSDK) {
                log('请先初始化SDK', 'error');
                return;
            }
            try {
                await dialogAvatarSDK.startRecording();
                log('开始录音成功');
            } catch (error) {
                log('开始录音失败: ' + error.message, 'error');
            }
        };
        
        document.getElementById('stopRecordBtn').onclick = () => {
            if (!dialogAvatarSDK) {
                log('请先初始化SDK', 'error');
                return;
            }
            try {
                dialogAvatarSDK.stopRecording();
                log('停止录音成功');
            } catch (error) {
                log('停止录音失败: ' + error.message, 'error');
            }
        };
        
        document.getElementById('sendTextBtn').onclick = async () => {
            if (!dialogAvatarSDK) {
                log('请先初始化SDK', 'error');
                return;
            }
            try {
                const text = document.getElementById('textInput').value.trim();
                if (!text) {
                    log('请输入要发送的文本', 'warning');
                    return;
                }
                await dialogAvatarSDK.sendText(text);
                log('发送文本成功: ' + text);
            } catch (error) {
                log('发送文本失败: ' + error.message, 'error');
            }
        };
        
        // 添加回车键发送功能
        document.getElementById('textInput').onkeypress = async (e) => {
            if (e.key === 'Enter') {
                document.getElementById('sendTextBtn').click();
            }
        };
        
        document.getElementById('destroyBtn').onclick = () => {
            if (!dialogAvatarSDK) {
                log('请先初始化SDK', 'error');
                return;
            }
            try {
                dialogAvatarSDK.destroy();
                dialogAvatarSDK = null;
                log('销毁实例成功');
                updateStatus('未初始化');
            } catch (error) {
                log('销毁实例失败: ' + error.message, 'error');
            }
        };
    </script>
</body>
</html> 